<template>
    <div class="report-list">
        <search-table 
        :total="total" 
        :page.sync="currentPage" 
        :size.sync="pageSize"
        @change-page="getReportList" 
        @change-size="getReportList(currentPage)"
        :columns="columns" 
        :data="reportList">
            <template slot="button-group">
                <Button
                    v-if="type === 7 && scoreMode === 1"
                    type="primary"
                    ghost
                    :disabled="disabledAllBtn"
                    @click="showUploadModal"
                    icon="md-options"
                    >提交报告</Button
                >
            </template>
            <template slot="select-group">
                <Select filterable
                    v-if="!teamId"
                    v-model="teamName"
                    placeholder="请选择团队"
                    filterable
                    clearable
                    @on-change="getReportList(1)"
                >
                    <Option
                        v-for="item in teamList"
                        :value="item.name"
                        :key="item.id"
                        :title="item.name"
                        >{{ item.name }}</Option
                    >
                </Select>
                <Select filterable
                    v-if="wpUpMode === 2"
                    v-model="questionName"
                    :placeholder="`请选择${typeName}`"
                    filterable
                    clearable
                    @on-change="getReportList(1)"
                >
                    <Option
                        v-for="(item, index) in questionList"
                        :value="item.name"
                        :key="index"
                        :title="item.name"
                        >{{ item.name }}</Option
                    >
                </Select>
            </template>
            <template slot="input-group">
                <Input v-model.trim="fileName" placeholder="请输入文件名" clearable />
            </template>
        </search-table>
        <Modal
            v-model="reportGradeModal.show"
            :title="reportGradeModal.title"
            :loading="reportGradeModal.loading"
            width="800px"
            @on-ok="reportGrade()"
            @on-cancel="closeModal"
            :mask-closable="false"
        >
            <Form
                ref="gradeValidate"
                :model="gradeValidate"
                :rules="ruleValidate"
                :label-width="120"
            >
                <FormItem label="攻击类型" prop="attackType" key="attackType">
                    <Select filterable
                        v-model="gradeValidate.attackType"
                        filterable
                        placeholder="攻击类型"
                        @on-change="changeAttackType"
                    >
                        <Option
                            :value="item.category"
                            v-for="(item, index) in selRuleList"
                            :key="`type-${item.id}-${index}`"
                            :title="item.category"
                            >{{ item.category }}</Option
                        >
                    </Select>
                </FormItem>
                <FormItem label="危害程度" prop="attackLevel">
                    <Select filterable v-model="gradeValidate.attackLevel" filterable placeholder="危害程度">
                        <Option
                            :value="item.mold"
                            v-for="(item, index) in attackLevelList"
                            :key="`level-${item.id}-${index}`"
                            :title="item.mold"
                            >{{ item.mold }}</Option
                        >
                    </Select>
                </FormItem>
                <FormItem label="类别" prop="targetType" v-if="avaiRuleList.length > 1">
                    <RadioGroup v-model="gradeValidate.targetType" type="button">
                        <Radio
                            v-for="item in avaiRuleList"
                            :label="item.targetType"
                            :key="item.id"
                            >{{
                                item.targetType === '1'
                                    ? '一类'
                                    : item.targetType === '2'
                                    ? '二类'
                                    : '三类'
                            }}</Radio
                        >
                    </RadioGroup>
                </FormItem>
                <FormItem label="危险等级" prop="level">
                    <!--  && gradeValidate.level -->
                    <RadioGroup v-model="gradeValidate.level" type="button">
                        <Radio label="high">高危</Radio>
                        <!-- :disabled="true" -->
                        <Radio label="middle">中危</Radio>
                        <Radio label="low">低危</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="审核意见" prop="approvalInfo">
                    <Input
                        v-model.trim="gradeValidate.approvalInfo"
                        clearable
                        type="textarea"
                        :maxlength="1000"
                        :autosize="{ minRows: 4, maxRows: 8 }"
                        placeholder="审核意见"
                    ></Input>
                </FormItem>
                <FormItem label="分值" prop="score">
                    <InputNumber
                        :min="0"
                        :step="1"
                        v-model="gradeValidate.score"
                        placeholder="请输入分值"
                    ></InputNumber>
                    <Alert
                        type="warning"
                        show-icon
                        v-show="currentRule && currentRule.description"
                        class="points-tip"
                        >分值标准：{{ currentRule.description }}</Alert
                        >
                </FormItem>
            </Form>
        </Modal>
        <ReportSubmit
            ref="submitReportModal"
            :zhSubmitTargetId="targetId"
            :zhSubmitTeamId="teamId"
            :drillDetail="drillDetail"
            :taskReportListData="taskList"
            @upload-success="getReportList(currentPage)"
        ></ReportSubmit>
    </div>
</template>

<script>
import SearchTable from '@/components/SearchTable/SearchTable';
import groupMixin from '@/mixin/groupMixin';
import { getReportList } from '@/api/compitionStatic';
import {
    queryCtfTarget,
    getTargetTeamList_new,
    queryHWScoreRule,
    reportGrade
} from '@/api/drill_compete';
import { getTaskList } from '@/api/drill';
import LevelMixin from '@/mixin/levelMixin';
import ReportSubmit from '@/view/drill_compete/page/hw/upload-submit';
export default {
    name: 'ReportList',
    mixins: [groupMixin, LevelMixin],
    components: {
        SearchTable,
        ReportSubmit,
    },
    props: {
        wpUpMode: {
            type: Number,
            default: 1,
        },
        type: {
            // 默认夺旗赛模式
            type: Number,
            default: 2,
        },
        disabledAllBtn: {
            type: Boolean,
        },
        targetId: {
            // 任务报告
            type: String,
            default: '',
        },
        teamId: {
            type: String,
            default: '',
        },
        disabledScore: {
            type: Boolean,
            default: false,
        },
        drillDetail: {
            type: Object,
            default: () => {
                return {
                    id: '',
                    name: '',
                    progress: 0,
                };
            },
        },
        scoreMode:{ //1 累加  0 单次
            type: Number,
            default: 0
        }
    },
    computed: {
        typeName() {
            return this.type === 7 ? '任务' : '题目';
        },
        attackLevelList() {
            if (!this.gradeValidate.attackType) {
                return [];
            }
            let list = this.selRuleList;
            let type = this.gradeValidate.attackType;
            return list.find((item) => item.value === type).children;
        },
        currentRule() {
            if (this.avaiRuleList.length >= 1) {
                return this.avaiRuleList[0];
            } else {
                return {
                    id: '',
                };
            }
            //   else if (this.avaiRuleList.length > 1 && this.gradeValidate.targetType) {
            //     return this.avaiRuleList.find((item) => item.targetType === this.gradeValidate.targetType);
            //   } else {
            //     return {
            //       id: ''
            //     };
            //   }
        },
        avaiRuleList() {
            let category = this.gradeValidate.attackType;
            if (!(category && this.gradeValidate.attackLevel)) {
                return [];
            }
            let ruleList = this.ruleList.filter(
                (item) => item.category === category && item.mold === this.gradeValidate.attackLevel
            );
            let avaiRuleList = ruleList.filter(
                (rule) => rule.targetType === this.currentTarget.category
            );
            return avaiRuleList.length > 0 ? avaiRuleList : ruleList;
        },
    },
    data() {
        const validatePoints = (rule, value, callback) => {
            if (value || value === 0) {
                if (!Number.isInteger(value)) {
                    callback(new Error('请输入整数'));
                } else {
                    if (value < 0 || value > 100000) {
                        callback(new Error('分值范围0~100000'));
                    } else {
                        callback();
                    }
                }
            } else {
                callback(new Error('不能为空'));
            }
        };
        return {
            questionList: [],
            reportGradeModal: {
                show: false,
                title: '评分',
                loading: true,
            },
            columns: [
                {
                    placement: 'top-left',
                    title: '团队名称',
                    key: 'teamName',
                    align: 'center',
                    tooltip: true,
                    width: 230,
                },
                {
                    title: '文件名',
                    width: 200,
                    key: 'fileName',
                    tooltip: true,
                },
                {
                    title: '提交者',
                    width: 120,
                    key: 'userName',
                    tooltip: true,
                },
                {
                    title: '创建时间',
                    width: 140,
                    key: 'createTime',
                },
                {
                    title: '得分',
                    width: 140,
                    key: 'score',
                    show: () => {
                        return this.type == 7 && this.scoreMode === 1? true : false;
                    },
                },
                {
                    title: '攻击类型',
                    width: 140,
                    key: 'attackTypeName',
                    show: () => {
                        return this.type == 7 && this.scoreMode === 1? true : false;
                    },
                    tooltip: true,
                },
                {
                    title: '危害程度',
                    width: 140,
                    key: 'attackLevel',
                    show: () => {
                        return this.type == 7 && this.scoreMode === 1 ? true : false;
                    },
                    tooltip: true,
                },
                {
                    title: '危险等级',
                    key: 'level',
                    width: 100,
                    tooltip: true,
                    render: (h, params) => {
                        let obj = this.mixinPaserLevel(params.row.level);
                        return h(
                            'span',
                            {
                                style: {
                                    color: obj.color,
                                },
                            },
                            obj.text
                        );
                    },
                    show: () => {
                        return this.type == 7 && this.scoreMode === 1? true : false;
                    },
                },
                {
                    title: '审核意见',
                    width: 140,
                    key: 'approvalInfo',
                    show: () => {
                        return this.type == 7 && this.scoreMode === 1? true : false;
                    },
                    tooltip: true,
                },
                {
                    title: '操作',
                    key: 'action',
                    placement: 'top-right',
                    width: 160,
                    opList: [
                        {
                            txt: '下载',
                            disabled: this.disabledAllBtn,
                            fun: (data) => {
                                this.download(data.fileId);
                            }
                        },
                        {
                            txt: '预览',
                            disabled: this.disabledAllBtn,
                            fun: (data) => {
                                window.open(`/api/minio/filePreview?id=${data.fileId}`);
                            }
                        },
                        {
                            txt: '评分',
                            disabled: this.disabledAllBtn || this.disabledScore,
                            show:(data) => {
                                return this.targetId && this.type == 7 && this.scoreMode === 1
                            },
                            fun:this.reviewBtn
                        }
                    ]
                },
                {
                    title: '操作',
                    action: true,
                    key: 'fileId',
                    placement: 'top-right',
                    show:false,
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'primary',
                                        size: 'small',
                                        disabled: this.disabledAllBtn,
                                    },
                                    style: {
                                        marginRight: '5px',
                                    },
                                    on: {
                                        click: () => {
                                            this.download(params.row.fileId);
                                        },
                                    },
                                },
                                '下载'
                            ),
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'primary',
                                        size: 'small',
                                        disabled: this.disabledAllBtn,
                                    },
                                    style: {
                                        marginRight: '5px',
                                    },
                                    on: {
                                        click: () => {
                                            window.open(
                                                `/api/minio/filePreview?id=${params.row.fileId}`
                                            );
                                        },
                                    },
                                },
                                '预览'
                            ),
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'primary',
                                        size: 'small',
                                        disabled: this.disabledAllBtn || this.disabledScore,
                                    },
                                    style: {
                                        marginRight: '5px',
                                        display: this.targetId && this.type == 7 && this.scoreMode === 1 ? '' : 'none', //综合演练的累加计分模式显示评分
                                    },
                                    on: {
                                        click: () => {
                                            this.reviewBtn(params.row);
                                        },
                                    },
                                },
                                '评分'
                            ),
                        ]);
                    },
                },
            ],
            total: 0, // 总记录数
            reportList: [], // 报告列表
            fileName: '', // 搜索条件，报告名称
            teamName: '', // 搜索条件，团队名称
            questionName: '', // 搜索条件，题目名称
            currentPage: 1, // 当前页
            pageSize: 10, // 分页大小
            gradeValidate: {
                sceneId: this.$route.query.id,
                attackType: '',
                approvalInfo: '',
                attackLevel: '',
                targetType: '',
                level: '',
                score: 0,
            },
            ruleValidate: {
                attackType: [{ required: true, message: '请选择攻击类型', trigger: 'change' }],
                attackLevel: [{ required: true, message: '请选择危害程度', trigger: 'change' }],
                // targetType: [{ required: true, message: '请选择目标类型', trigger: 'change' }],
                approvalInfo: [
                    { required: true, min: 1, message: '请填写审核意见', trigger: 'change' },
                ],
                // level: [{ required: true, message: '请选择危险等级', trigger: 'change' }],
                score: [
                    {
                        required: true,
                        type: 'number',
                        validator: validatePoints,
                        trigger: 'change',
                    },
                ],
            },
            ruleList: [],
            selRuleList: [],
            currentTarget: {},
            taskList: [],
        };
    },
    watch: {
        fileName(val) {
            clearTimeout(this.timer);
            this.timer = setTimeout(() => {
                this.getReportList();
            }, 200);
        },
        currentRule(val, oldVal) {
            if (val && val.id && this.isCheckFirst) {
                //第一次不使用规则的信息回显
                if(this.gradeValidate.status !== 2){ //没有评分过
                    this.gradeValidate.score = val.score || 0;
                    this.gradeValidate.level = val.grade;
                    this.gradeValidate.description = val.description;
                }
                this.isCheckFirst = false;
                return;
            }
            if (val.id !== oldVal.id && val.id) {
                this.gradeValidate.score = val.score || 0;
                this.gradeValidate.level = val.grade;
                this.gradeValidate.description = val.description;
            } else {
            }
        },
    },
    mounted() {
        this.$nextTick(() => {
            this.getReportList();
            if (this.type == 7) {
                this.queryHWScoreRule();
                this.getTaskList();
            }
            if (this.wpUpMode === 2) {
                this.getQuestionList();
                this.columns.splice(1, 0, {
                    title: this.typeName,
                    width: 120,
                    key: 'questionName',
                    tooltip: true,
                });
            }
        });
    },
    methods: {
        // 获取题目列表
        getQuestionList() {
            if (this.type === 2) {
                // 夺旗赛查询题目列表
                queryCtfTarget(this.$route.query.id, {
                    pageIndex: 1,
                    pageSize: 2147483647,
                }).then(({ code, message, data }) => {
                    if (code !== 1) {
                        this.$Message.warning(message);
                        return;
                    }
                    this.questionList = data.items;
                });
            } else {
                // 其他类型查询靶标列表
                getTargetTeamList_new({
                    pageIndex: 1,
                    pageSize: 2147483647,
                    sceneId: this.$route.query.id,
                    projectId: this.$route.query.prjid,
                }).then(({ code, message, data }) => {
                    if (code !== 1) {
                        this.$Message.warning(message);
                        return;
                    }
                    this.questionList = data.items;
                    console.log(this.questionList);
                });
            }
        },
        // 下载报告
        download(fileId) {
            let a = document.createElement('a');
            document.body.appendChild(a);
            a.href = `/api/minio/download/${fileId}`;
            a.click(); //点击触发下载
            // window.URL.revokeObjectURL(url); //下载完成进行释放
        },
        // 获取报告列表
        getReportList(pageNow) {
            this.currentPage = pageNow || 1;
            getReportList(this.$route.query.id, {
                pageIndex: this.currentPage,
                pageSize: this.pageSize,
                teamName: this.teamName,
                fileName: this.fileName,
                questionName: this.questionName,
                teamId: this.teamId,
                questionId: this.targetId,
            })
                .then(({ code, data, message }) => {
                    if (code === 1) {
                        this.reportList = data.items || [];
                        this.reportList.forEach((item) => {
                            let currentRule = this.ruleList.find(
                                (rule) => rule.id == item.attackType
                            );
                            if (currentRule) {
                                item.attackTypeName = currentRule.category;
                                item.attackLevel = currentRule.mold;
                            } else {
                                item.attackTypeName = '';
                                item.attackLevel = '';
                            }
                        });
                        this.total = data.total || 0;
                    } else {
                        this.$Message.error(message);
                    }
                })
                .catch((error) => {
                    this.$Message.error('查询报告列表异常');
                });
        },
        reportGrade() {
            this.$refs.gradeValidate
                .validate((valid) => {
                    if (valid) {
                        let params = {
                            sceneId: this.$route.query.id,
                            questionId: this.currentTarget.questionId,
                            teamId: this.currentTarget.teamId,
                            score: 0,
                            ctfReport: {
                                status: 2,
                                id: this.currentTarget.id,
                                fileId: this.currentTarget.fileId,
                                attackType: this.currentRule.id,
                                approvalInfo: this.gradeValidate.approvalInfo,
                                attackLevel: this.currentRule.mold,
                                // targetType: currentRule.targetType,
                                score: this.gradeValidate.score || 0,
                                level: this.gradeValidate.level,
                            },
                        };
                        reportGrade(params)
                            .then((data) => {
                                if (data.code == 1) {
                                    this.reportGradeModal.show = false;
                                    this.$Message.info('操作成功');
                                    this.getReportList(this.currentPage);
                                } else {
                                    this.cancelLoading();
                                    this.$Message.warning(data.message);
                                }
                            })
                            .catch((error) => {
                                this.cancelLoading();
                            });
                    } else {
                        this.cancelLoading();
                    }
                })
                .catch(() => {
                    this.cancelLoading();
                });
        },
        cancelLoading() {
            this.reportGradeModal.loading = false;
            setTimeout(() => {
                this.reportGradeModal.loading = true;
            }, 500);
        },
        closeModal() {
            this.$refs['gradeValidate'].resetFields();
        },
        reviewBtn(row) {
            this.$refs['gradeValidate'].resetFields();
            this.currentTarget = row;
            let type = 'attackType';
            let currentRule = this.ruleList.find((item) => item.id === row[type]) || {};
            this.isCheckFirst = row.attackType ? true : false;
            this.gradeValidate = {
                attackType: currentRule.category,
                approvalInfo: row.approvalInfo,
                attackLevel: currentRule.mold,
                // targetType: currentRule.targetType,
                score: row.score || 0,
                level: row.level,
                status: row.status
            };
            this.reportGradeModal.show = true;
        },
        changeAttackType() {
            this.gradeValidate.attackLevel = '';
            this.gradeValidate.targetType = '';
            this.gradeValidate.score = 0;
            this.gradeValidate.level = '';
        },
        queryHWScoreRule() {
            return new Promise((resolve, reject) => {
                let query = { pageIndex: 1, pageSize: 100000 };
                queryHWScoreRule(this.$route.query.id, query)
                    .then(({ code, data, message }) => {
                        if (code == 1) {
                            this.ruleList = data.items;
                            //攻击还是防御
                            let ruleList = data.items;
                            let ruleObj = {};
                            ruleList.forEach((rule) => {
                                if (!ruleObj[rule.category]) {
                                    ruleObj[rule.category] = {
                                        ...rule,
                                        label: rule.category,
                                        value: rule.category,
                                        children: [rule],
                                    };
                                } else {
                                    if (
                                        !ruleObj[rule.category].children.find(
                                            (item) => item.mold === rule.mold
                                        )
                                    ) {
                                        ruleObj[rule.category].children.push(rule);
                                    }
                                }
                            });
                            this.selRuleList = Object.values(ruleObj);
                            console.log(this.selRuleList);
                            resolve();
                        } else {
                            this.$Message.error(message);
                        }
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            });
        },
        getTaskList() {
            getTaskList({
                testId: this.$route.query.id,
                taskMode: 'preset',
            }).then((response) => {
                if (response.code == 1) {
                    this.taskList = response.data.items;
                } else if (response.code == -2) {
                } else {
                    $this.$Message.error(response.message);
                }
            });
        },
        // 显示提交报告modal
        showUploadModal() {
            this.$refs.submitReportModal.openModal();
        },
    },
};
</script>

<style scoped>
    .points-tip {
        margin-top: 4px;
        word-wrap: break-word;
        word-break: break-all;

    }
</style>
